import 'dart:async';

import 'package:flutter/material.dart';
import '../widget/image.dart';

class Swiper extends StatefulWidget {
  final double width;
  final double height;
  final List<String> list;

  const Swiper({
    super.key,
    required this.list,
    this.width = double.infinity,
    this.height = 200,
  });

  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  int _currentIndex = 0;
  List<Widget> pageList = [];
  late PageController _pageController;
  late Timer timer;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    for (int i = 0; i < widget.list.length; i++) {
      pageList.add(ImageWidget(scr: widget.list[i], height: widget.height));
    }
    _pageController = PageController(initialPage: 0);

    timer=Timer.periodic(Duration(seconds: 5), (time) {
      _pageController.animateToPage(
        (_currentIndex + 1) % pageList.length,
        duration: Duration(milliseconds: 200),
        curve: Curves.linear,
      );
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: widget.height,
          child: PageView.builder(
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index % pageList.length;
              });
            },
            itemCount: 1000,
            itemBuilder: (BuildContext context, int index) {
              return pageList[index % pageList.length];
            },
          ),
        ),
        Positioned(
          bottom: 2,
          left: 0,
          right: 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(pageList.length, (index) {
              return Container(
                width: 10,
                height: 10,
                margin: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  color: _currentIndex == index ? Colors.white : Colors.grey,
                  shape: BoxShape.circle,
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
